package cn.finyzq.ss.games.web.interceptor;

import cn.finyzq.ss.games.utils.ResultCode;
import cn.finyzq.ss.games.utils.SessionUtils;
import cn.finyzq.ss.games.vo.ResultBean;
import cn.finyzq.ss.games.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Create Time: 2018年08月05日 12:51
 *
 * @author fin
 */
public class AuthInterceptor extends AbstractInterceptor {

    /** logger */
    private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("location: {}, method: {}", httpServletRequest.getRequestURL().toString(),httpServletRequest.getMethod());
        User user = SessionUtils.getUser(httpServletRequest);
        if(!isPublic((HandlerMethod) o)){
            if(user == null){
//                user = new User();
//                user.setOpenid("fin");
//                SessionUtils.setUser(httpServletRequest, user);
//                return true;
                return error(httpServletResponse);
            }else{
                return true;
            }
        }
        return true;
    }

    private boolean error(HttpServletResponse httpServletResponse) throws IOException {
        ResultBean resultBean = new ResultBean(ResultCode.NO_ACCESS, "需要登录");
        httpServletResponse.getOutputStream().write(resultBean.toString().getBytes());

        return false;
    }

}
